﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

public partial class CRM_Manager_ERP_SalesPlanEdit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int c = BindCenterStore(Store_Rome, Request.QueryString["ptabid"]);
            if (c > 0)
                extcomb_StoreRoomId.SelectedIndex = 0;
            string objid = ViewState_ObjID = string.IsNullOrEmpty(Request.QueryString["ObjId"]) ? "Add" : Request.QueryString["ObjId"];
            ShowEditInfo(objid);
        }
    }

    private void ShowEditInfo(string objid)
    {
        if (objid == "Add")
        {
            exttxtf_InUserName.Text = BS_LoginUserName;
            exthidn_InUser.Text = BS_LoginUserID;
            exttxtf_InDate.Text = DateTime.Now.ToDateTimeString();
        }
        else
        {
            var planDataTable = CRMMis.BLL.ERP_SalesPlan.GetList("SalesPlanId=" + objid).Tables[0];
            if (planDataTable.Rows.Count > 0)
            {
                DataRow row = planDataTable.Rows[0];
                int planState = Convert.ToInt32(row["State"]);
                //根据状态控制
                if (planState != 1)
                    extBtn_CheckInfo.Hidden = true;
                if (planState > 0)
                {
                    extBtn_SubmitInfo.Hidden = true;
                    extBtn_Save.Hidden = true;
                    extBtn_AddItem.Hidden = extBtn_DeleteItem.Hidden = true;
                    SetContainerReadOnly(formPanel, true);
                    gridPanel_listdata.ColumnModel.Columns[1].Editable =                //商品名称
                        gridPanel_listdata.ColumnModel.Columns[6].Editable = false;     //数量
                }
                if (planState > 1)
                {
                    extBtn_CheckInfo.Hidden = true;
                }
                SetContainer(formPanel, planDataTable);
                //单独绑定客户
                DataTable suppData = CRMMis.BLL.ERP_Customer.GetList("CustomerId=" + row["CustomerId"], "CustomerName,Spell,Address").Tables[0];
                Store_Customer.DataSource = suppData;
                Store_Customer.DataBind();

                var planDetail = CRMMis.BLL.ERP_SalesPlanDetail.GetList(" DSalesPlanId=" + objid).Tables[0];
                Store1.DataSource = planDetail;
                Store1.DataBind();
            }
        }
    }

    [DirectMethod]
    public void BindCargoComb(string searchText)
    {
        string sqWhere = " CustomerId="
            + Convert.ToInt32(extcomb_CustomerId.Value) + " ";
        if (!string.IsNullOrEmpty(searchText))
        {
            sqWhere += " and( CargoName like '%" + FilterSpecChar(searchText) + "%' or Spell like '%" + FilterSpecChar(searchText) + "%') ";
        }
        var datatable = CRMMis.BLL.ERP_CusCargo.GetCargoList(sqWhere, " CargoName asc").Tables[0];
        store_Cargo.DataSource = datatable;
        store_Cargo.DataBind();
    }

    /// <summary>
    /// 保存，
    /// </summary>
    /// <param name="jsonData"></param>
    /// <param name="type">0,保存;1,提交;2,审核</param>
    [DirectMethod]
    public void SaveData(string jsonData,int type)
    {
        List<CRMMis.Model.ERP_SalesPlanDetail> details = JSON.Deserialize<List<CRMMis.Model.ERP_SalesPlanDetail>>(jsonData);
        CRMMis.Model.ERP_SalesPlan planModel;
        if (ViewState_ObjID == "Add")
        {
            planModel = new CRMMis.Model.ERP_SalesPlan();
            planModel.SalesPlanId = CRMMis.BLL.ERP_SalesPlan.GetNewID();
            planModel.SalesPlanNo = GetBusinessNo("XS", "ERP_SalesPlanXS", Convert.ToInt32(extcomb_StoreRoomId.Value).ToString("000"));
            planModel.InUser = BS_LoginUserID;
            planModel.InDate = exttxtf_InDate.Text.Trim();
            planModel.State = 0;
            if (type == 1)
                planModel.State = 1;    //提交
        }
        else
        {
            planModel = CRMMis.BLL.ERP_SalesPlan.GetModel(Convert.ToInt32(ViewState_ObjID));
            if (type == 1)
            {
                if (planModel.State == 0)
                    planModel.State = 1;    //提交
                else
                {
                    X.Msg.Alert("系统提示", "提交失败！当前记录已经提交").Show();
                    return;
                }
            }
            else if (type == 2)
            {
                if (planModel.State == 1)
                    planModel.State = 2;    //审核
                else
                {
                    X.Msg.Alert("系统提示", "审核失败！当前记录已经审核").Show();
                    return;
                }
            }
        }
        if (type < 2)
        {
            planModel.StoreRoomId = Convert.ToInt32(extcomb_StoreRoomId.Value);
            planModel.CustomerId = Convert.ToInt32(extcomb_CustomerId.Value);
            planModel.Remark = exttxtf_Remark.Text.Trim();
        }
        CommonLib.BLL.MyTransaction myTrans = new CommonLib.BLL.MyTransaction();
        myTrans.BeginTransaction();
        try
        {
            if (ViewState_ObjID == "Add")
            {
                CRMMis.BLL.ERP_SalesPlan.Add(myTrans, planModel);
            }
            else
            {
                CRMMis.BLL.ERP_SalesPlan.Update(myTrans, planModel);
                //删除子表
                if (type < 2)
                    CRMMis.BLL.ERP_SalesPlanDetail.DeleteFK(myTrans, "DSalesPlanId = " + planModel.SalesPlanId);
            }
            if (type < 2)
            {
                foreach (CRMMis.Model.ERP_SalesPlanDetail detailModel in details)
                {
                    detailModel.DetailId = CRMMis.BLL.ERP_SalesPlanDetail.GetNewID();
                    detailModel.DSalesPlanId = planModel.SalesPlanId;
                    CRMMis.BLL.ERP_SalesPlanDetail.Add(myTrans, detailModel);
                }
            }
            myTrans.CommitTran();
            ViewState_ObjID = planModel.SalesPlanId.ToString();
            exttxtf_SalesPlanNo.Text = planModel.SalesPlanNo;

            string handler = "";
            if (type > 0)
                handler = "closeCurrTab();";
            X.Msg.Alert("系统提示", "保存成功！", handler).Show();
        }
        catch(Exception ex)
        {
            myTrans.RollBackTran();
            X.Msg.Alert("系统提示", "保存失败！</br>" + ex.Message).Show();
        }
    }


    #region 客户选择

    protected void StoreCustomer_Refresh(object sender, StoreRefreshDataEventArgs e)
    {
        var qStr = GetCustomerQryString();
        int recordcount = CRMMis.BLL.ERP_Customer.GetRecorderCount(qStr);
        int PageSize = extcomb_CustomerId.PageSize;
        int CurPage = e.Start / PageSize + 1;
        e.Total = recordcount;
        DataTable suppData = CRMMis.BLL.ERP_Customer.GetPageList(PageSize, CurPage, qStr, "CustomerName,Spell,Address").Tables[0];
        Store_Customer.DataSource = suppData;
        Store_Customer.DataBind();
    }

    private string GetCustomerQryString()
    {
        string StrSql = "DelState=0 ";
        string selText = FilterSpecChar(extcomb_CustomerId.SelectedItem.Text.Trim());
        if (!string.IsNullOrEmpty(selText))
            StrSql += " and ( CustomerName like '%" + selText + "%' or Spell like '%" + selText + "%') ";
        return StrSql;
    }

    #endregion
    #region Excel导入

    ///<summary>
    /// 上传Excel
    ///</summary>
    [DirectMethod]
    public void ImportExcel()
    {
        if (extcomb_CustomerId.Text == "")
        {
            X.Msg.Alert("系统提示", "请先选择客户！").Show();
            return;
        }
        if (extFuf_ImportExcel.HasFile)
        {
            string strExt = string.Empty;
            string strName = "";
            string strPathName = "";
            string sSize = "";

            if (extFuf_ImportExcel.PostedFile != null && extFuf_ImportExcel.PostedFile.ContentLength > 0)
            {
                strName = extFuf_ImportExcel.PostedFile.FileName;
                sSize = extFuf_ImportExcel.PostedFile.ContentLength.ToString();
                strExt = System.IO.Path.GetExtension(strName);
                strPathName = Guid.NewGuid().ToString() + strExt;
                if (strExt.ToUpper() != ".XLS" && strExt.ToUpper() != ".XLSX")
                {
                    X.Msg.Alert("提示", "Excel格式应为.xls，xls", MessageBox.Icon.WARNING).Show();
                    return;
                }
            }

            string strMapPath = Server.MapPath("../TmpFile/");
            string strPath = strMapPath + strPathName;
            extFuf_ImportExcel.PostedFile.SaveAs(strPath);
            OpenExcel(strPath, strExt);
        }
        else
        {
            X.Msg.Alert("提示", "请选择Excel", MessageBox.Icon.NONE).Show();
        }
    }


    public DataTable SessionImportDetailExcel { get; set; }

    private void OpenExcel(string filePath, string strExt)
    {
        System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);//读入excel模板
        IWorkbook Iworkbook = null;
        if (strExt.ToUpper() == ".XLSX") // 2007版本
            Iworkbook = new XSSFWorkbook(stream);
        else if (strExt.ToUpper() == ".XLS") // 2003版本
            Iworkbook = new HSSFWorkbook(stream);

        //处理模板数据
        ISheet sheet = Iworkbook.GetSheetAt(0);

        IRow headerRow = sheet.GetRow(0);
        int cellCount = headerRow.LastCellNum;  //LastCellNum = PhysicalNumberOfCells
        int rowCount = sheet.LastRowNum;        //LastRowNum = PhysicalNumberOfRows - 1

        SessionImportDetailExcel = new DataTable();

        foreach (var column in gridPanel_listdata.ColumnModel.Columns)
        {
            SessionImportDetailExcel.Columns.Add(column.DataIndex);
        }

        for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
        {
            IRow row = sheet.GetRow(i);
            DataRow dataRow = SessionImportDetailExcel.NewRow();

            if (row != null)
            {
                //dataRow["ItemlId"] = i;
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        string val = GetCellValue(row.GetCell(j));
                        dataRow[j + 1] = val;
                    }
                }
            }
            SessionImportDetailExcel.Rows.Add(dataRow);
        }
        SetExcelData();

    }

    /// <summary>
    /// 根据Excel列类型获取列的值
    /// </summary>
    /// <param name="cell">Excel列</param>
    /// <returns></returns>
    private static string GetCellValue(ICell cell)
    {
        if (cell == null)
            return string.Empty;
        switch (cell.CellType)
        {
            case CellType.Blank:
                return string.Empty;
            case CellType.Boolean:
                return cell.BooleanCellValue.ToString();
            case CellType.Error:
                return cell.ErrorCellValue.ToString();
            case CellType.Numeric:
            case CellType.Unknown:
            default:
                return cell.ToString();
            case CellType.String:
                return cell.StringCellValue;
            case CellType.Formula:
                try
                {
                    HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                    e.EvaluateInCell(cell);
                    return cell.ToString();
                }
                catch
                {
                    return cell.NumericCellValue.ToString();
                }
        }
    }

    private void SetExcelData()
    {
        var ViewState_InStoreList = CRMMis.BLL.ERP_SalesPlanDetail.GetList("1=2", "").Tables[0];
        string tmp = " State=1 and CargoName='{0}' and Spec='{1}' and Version='{2}' and ProduceName='{3}' and Area='{4}' ";
        tmp += " and CustomId=" + extcomb_CustomerId.SelectedItem.Value;
        int index = 2;
        foreach (DataRow row in SessionImportDetailExcel.Rows)
        {
            DataTable dtCargo_Detail = CRMMis.BLL.ERP_CusCargo.GetCargoList(string.Format(tmp, row["CargoName"], row["Spec"], row["Version"], row["ProduceName"], row["Area"]),"").Tables[0];
            if (dtCargo_Detail.Rows.Count < 1)
            {
                X.Msg.Alert("系统提示", "第" + index + "行,该商品没有目录信息，无法添加").Show();
                return;
            }
            DataRow dr = dtCargo_Detail.Rows[0];
            var nrow = ViewState_InStoreList.NewRow();
            nrow["CargoName"] = dr["CargoName"];
            nrow["Spec"] = dr["Spec"];
            nrow["Version"] = dr["Version"];
            nrow["ProduceName"] = dr["ProduceName"];
            nrow["Area"] = dr["Area"];
            nrow["Unit"] = dr["Unit"];
            nrow["DCargoId"] = dr["BsCargoId"];
            nrow["DCusCargoId"] = dr["CargoId"];
            nrow["DCount"] = row["DCount"];
            nrow["DetailId"] = -index;
            ViewState_InStoreList.Rows.Add(nrow);
            index++;
        }
        Store1.DataSource = ViewState_InStoreList;
        Store1.DataBind();

    }


    #endregion

}